/*
 * @Descripttion: 
 * @Author: zhangchong zc16607@gmail.com
 * @Date: 2024-02-07 13:43:32
 * @LastEditors: zhangchong zc16607@gmail.com
 * @LastEditTime: 2024-02-08 11:28:32
 */
const got = require('./got')
const { getKey } = require('./fileDb')
const { obj2url } = require('./index')
const nasToolConfig = getKey('nastool')

// nas-tools系统登录, 获取token
async function loginNasTool() {
  const loginRes = await got(nasToolConfig.baseUrl + '/user/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: obj2url({ username: nasToolConfig.account, password: nasToolConfig.password })
  }).json()
  if (loginRes.data && loginRes.data.token) {
    let token = loginRes.data.token
    process.env.ntToken = token
    return token
  }
  return ''
}

async function commonReq(url, type, data) {
  let token = process.env.ntToken || ''
  if (!token) token = await loginNasTool()

  // 目前用到的接口都是post请求
  let res = await got(nasToolConfig.baseUrl + url, {
    method: 'POST',
    headers: { Authorization: token, 'Content-Type': 'application/x-www-form-urlencoded', 'cookie': nasToolConfig.cookie || '' },
    body: obj2url(data)
  }).json()
  // token失效处理
  if (res.code === 403) {
    loginNasTool()
    return
  } else {
    return res
  }
}

module.exports = { commonReq }